<template>
  <div class="workspace">
    <div class="workspace__inner">
      <el-card class="workspace__card">
        <div class="workspace__header">
          <div class="workspace__profile">
            <t-avatar
              :name="userInfos.nickName"
              :size="64"
              :url="userInfos.avatar"
            ></t-avatar>
            <div class="workspace__info">
              <h1 class="workspace__title">{{ $t("system.workspace.greeting.title") }},{{ userInfos.nickName }}</h1>
              <p class="workspace__greeting">{{ greetingMessage }}</p>
            </div>
          </div>
          <div class="workspace__datetime">
            <div class="workspace__time">{{ currentTime }}</div>
            <div class="workspace__date">{{ currentDate }}</div>
          </div>
        </div>
        <div class="workspace__login-time">{{ $t("system.workspace.lastLogin") }}{{ formattedLastLoginTime }}</div>
      </el-card>

      <el-card class="workspace__card">
        <template #header>
          <div class="workspace__header fun-list-header">
            <h2 class="workspace__section-title">{{ $t("system.workspace.commonFunctions") }}</h2>
            <el-button
              class="workspace__customize-btn"
              text
              type="primary"
            >
              <!-- <el-icon class="mr-1"><Setting /></el-icon> -->
            </el-button>
          </div>
        </template>
        <div class="workspace__functions">
          <template
            v-for="(item, index) in quickFunctions"
            :key="index"
          >
            <el-card
              v-if="allRoutePaths.includes(item.path)"
              class="function-card"
              shadow="hover"
              @click="handleFunctionClick(item.path)"
            >
              <div
                :class="['function-card__icon']"
                :style="{ backgroundColor: item.bgColor }"
              >
                <i
                  :class="['function-card__icon-inner', item.iconColor, item.icon]"
                  :size="28"
                ></i>
              </div>
              <h3 class="function-card__title">{{ item.title }}</h3>
            </el-card>
          </template>
        </div>
      </el-card>

      <el-card class="workspace__card">
        <template #header>
          <div class="workspace__header notices-header">
            <h2 class="workspace__section-title">{{ $t("system.workspace.notifications.title") }}</h2>
            <el-button
              class="workspace__more-btn"
              text
              type="primary"
              @click="router.push('/msg/my')"
            >
              {{ $t("system.workspace.notifications.viewMore") }}
              <el-icon class="ml-1">
                <ele-ArrowRight />
              </el-icon>
            </el-button>
          </div>
        </template>
        <div class="notices">
          <div
            v-for="(notice, index) in notices"
            :key="index"
            class="notices__item"
            @click="
              router.push({
                path: '/msg/my',
                query: { msgId: notice.anntId }
              })
            "
          >
            <div class="notices__content">
              <el-tag
                :type="notice.priority === 'H' ? 'danger' : 'info'"
                effect="light"
                size="small"
              >
                {{
                  notice.priority === "H"
                    ? $t("system.workspace.notifications.priority.high")
                    : $t("system.workspace.notifications.priority.normal")
                }}
              </el-tag>
              <span>{{ notice.title }}</span>
              <el-tag
                v-if="!notice.readFlag"
                effect="light"
                size="small"
                type="primary"
              >
                {{ $t("system.workspace.notifications.new") }}
              </el-tag>
            </div>
            <span class="notices__time">{{ notice.sendTime }}</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onBeforeMount, onBeforeUnmount, onMounted, ref } from "vue";
import { useUserInfo } from "@/stores/userInfo";
import { storeToRefs } from "pinia";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import "dayjs/locale/en";
import localeData from "dayjs/plugin/localeData";
import { i18n } from "@/i18n";
import { useRouter } from "vue-router";
import { useRoutesList } from "@/stores/routesList";
import { getMyAnnouncementSend, Message } from "@/api/system/announcement";

// 初始化 dayjs 配置
dayjs.extend(localeData);
dayjs.locale("zh-cn"); // 默认使用中文

const currentTime = ref("");
const currentDate = ref("");
let timer: number;

const updateDateTime = () => {
  const now = dayjs();

  // 更新时间
  currentTime.value = now.format("HH:mm");

  // 更新日期
  const weekdayIndex = now.day();
  const weekday = i18n.global.t(`system.workspace.datetime.weekdays.${weekdayIndex}`);

  currentDate.value =
    now.format(
      `YYYY[${i18n.global.t("system.workspace.datetime.year")}]MM[${i18n.global.t("system.workspace.datetime.month")}]DD[${i18n.global.t("system.workspace.datetime.day")}] `
    ) +
    i18n.global.t("system.workspace.datetime.weekday") +
    weekday;
};

onMounted(() => {
  updateDateTime();
  timer = window.setInterval(updateDateTime, 60000);
});

onBeforeUnmount(() => {
  clearInterval(timer);
});

const userInfo = useUserInfo();
const { userInfos } = storeToRefs(userInfo);

// 使用 dayjs 格式化时间戳
const formattedLastLoginTime = computed(() => {
  return dayjs(userInfos.value.time).format("YYYY-MM-DD HH:mm:ss");
});

const router = useRouter();

const handleFunctionClick = (path: string) => {
  router.push(path);
};

const quickFunctions = ref([
  {
    icon: "icon-yonghuguanli iconfont",
    title: i18n.global.t("menu.menuName.userManagement"),
    bgColor: "#4c4edb", // 主题色
    iconColor: "text-white",
    path: "/user/list"
  },
  {
    icon: "icon-jiaoseguanli iconfont",
    title: i18n.global.t("menu.menuName.roleManagement"),
    bgColor: "#67C23A", // Element UI 成功色
    iconColor: "text-white",
    path: "/user/role"
  },
  {
    icon: "icon-bumenguanli iconfont",
    title: i18n.global.t("menu.menuName.departmentManagement"),
    bgColor: "#E6A23C", // Element UI 警告色
    iconColor: "text-white",
    path: "/user/dept"
  },
  {
    icon: "icon-gangweiguanli iconfont",
    title: i18n.global.t("menu.menuName.positionManagement"),
    bgColor: "#5e60e6", // 主题色变体
    iconColor: "text-white",
    path: "/user/post"
  },
  {
    icon: "icon-shujuwajue iconfont",
    title: i18n.global.t("menu.menuName.workflowList"),
    bgColor: "#9C27B0", // 紫色
    iconColor: "text-white",
    path: "/workflow/list"
  },
  {
    icon: "icon-timu-04 iconfont",
    title: i18n.global.t("menu.menuName.formControl"),
    bgColor: "#0096c7", // 青色
    iconColor: "text-white",
    path: "/form/mange"
  },
  {
    icon: "icon-gengduo iconfont",
    title: i18n.global.t("menu.menuName.formQuestionBank"),
    bgColor: "#f76707", // 橙色
    iconColor: "text-white",
    path: "/question/bank"
  },
  {
    icon: "icon-xitongshezhi iconfont",
    title: i18n.global.t("menu.menuName.systemConfiguration"),
    bgColor: "#F56C6C", // Element UI 危险色
    iconColor: "text-white",
    path: "/sys/evnconfig"
  }
]);

const routesListStore = useRoutesList();
const { routesList } = storeToRefs(routesListStore);

// 递归获取所有路由路径
const getAllPaths = (routes: any[]): string[] => {
  let paths: string[] = [];

  routes.forEach(route => {
    // 如果存在path且不是外链，则添加到路径数组
    if (route.path && !route.isLink) {
      paths.push(route.path);
    }

    // 如果有子路由，递归获取子路由的路径
    if (route.children && route.children.length > 0) {
      paths = paths.concat(getAllPaths(route.children));
    }
  });

  return paths;
};

// 获取所有路由路径
const allRoutePaths = ref(getAllPaths(routesList.value || []));

const notices = ref<Message[]>([]);

onBeforeMount(() => {
  getMyAnnouncementSend({ current: 1, size: 10, msgCategory: "NOTICE", delFlag: false }).then(response => {
    notices.value = response.data.records;
  });
  // 如果不包含 则直接重定向到404
  console.log(userInfos.value.authBtnList);
  if (!userInfos?.value?.authBtnList.includes("system:mange:home") && !userInfos?.value?.authBtnList.includes("*:*:*")) {
    router.push("/404");
  }
});

const greetingMessage = computed(() => {
  const now = new Date();
  const hour = now.getHours();
  if (hour < 12) {
    return i18n.global.t("system.workspace.greeting.morning");
  } else if (hour < 18) {
    return i18n.global.t("system.workspace.greeting.afternoon");
  } else {
    return i18n.global.t("system.workspace.greeting.evening");
  }
});
</script>

<style lang="scss" scoped>
.workspace {
  background-color: #f9fafb;
  //   min-height: 1024px;

  &__inner {
    max-width: 1440px;
    margin: 0 auto;
    padding: 24px 32px;
  }

  &__card {
    background-color: #ffffff;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 24px;
    border: none;
  }

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px;
  }

  &__profile {
    display: flex;
    align-items: center;
    gap: 24px;
  }

  &__info {
    display: flex;
    flex-direction: column;
  }

  &__title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 8px;
    color: #1a1a1a;
  }

  &__greeting {
    font-size: 14px;
    color: #666;
  }

  &__datetime {
    text-align: right;
  }

  &__time {
    font-size: 23px;
    font-weight: 500;
    margin-bottom: 4px;
    color: #1a1a1a;
  }

  &__date {
    font-size: 14px;
    color: #999;
  }

  &__login-time {
    padding: 0 24px 16px;
    font-size: 13px;
    color: #999;
  }

  &__section-title {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
  }

  &__customize-btn,
  &__more-btn {
    display: flex;
    align-items: center;

    &:hover {
      background-color: rgba(64, 158, 255, 0.1);
    }
  }

  &__functions {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 24px;
    padding: 24px;
  }
}

.fun-list-header {
  padding: 10px;
}

.function-card {
  transition: all 0.3s ease;
  text-align: center;
  padding: 16px;
  border: none;
  cursor: pointer;

  &:hover {
    transform: translateY(-4px);
  }

  &__icon {
    padding: 16px;
    border-radius: 12px;
    margin: 0 auto 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
  }

  &__icon-inner {
    font-size: 1.75rem;
    color: #ffffff;
  }

  &__title {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
    margin: 0;
  }
}

.notices-header {
  padding: 10px;
}

.notices {
  margin-top: 16px;

  &__item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background-color: #f9fafb;
    }
  }

  &__content {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  &__time {
    color: #9ca3af;
    font-size: 0.875rem;
  }
}

:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-card__header) {
  padding: 0px;
}

@media (min-width: 2560px) {
  .workspace {
    &__inner {
      max-width: 1920px;
      padding: 48px 64px;
    }

    &__title {
      font-size: 1.5rem;
    }

    &__greeting {
      font-size: 1rem;
    }

    &__time {
      font-size: 2rem;
    }

    &__date {
      font-size: 1rem;
    }

    &__section-title {
      font-size: 1.5rem;
    }
  }

  .function-card {
    &__title {
      font-size: 1.125rem;
    }
  }

  .notices {
    &__time {
      font-size: 1rem;
    }
  }
}
</style>
